﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MplusM.MovieDatabaseWorkers;

namespace cz.muni.fi.pb138
{
    public partial class MainForm : Form
    {
        private MediaManager manager = MediaManager.Single;

        public MainForm()
        {
            InitializeComponent();

            manager.DatabaseChanged += (sender, e) => ShowAllMedias();
            ShowAllMedias();
        }

		/// <summary>
		/// sets the basic features of the MainForm form
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            ToolTip t = new ToolTip();
            t.SetToolTip(pctImportDetailsAdd, "Import medium details from...");
            t.SetToolTip(pctImportDetails, "Import medium details from...");
            t.SetToolTip(pctLoadCoverFromFileAdd, "Load image from file...");
            t.SetToolTip(pctLoadCoverFromFile, "Load image from file...");
        }

		/// <summary>
		/// Displays all the media that are stored in the database in a mediumList
		/// </summary>
        private void ShowAllMedias()
        {
            manager.FindAllMedias();
            this.mediumList.Items.Clear();
            this.mediumList.Items.AddRange(TransformMediaListToListViewData(manager.Medias));
            if (manager.Medias.Count > 0)
            {
                this.mediumList.Items[0].Selected = true;
                this.mediumList.Select();
            }
            else
            {
                ClearMediaDetails();
            }
        }

		/// <summary>
		/// Displays all the media that contain the string given in the name parameter and updates the mediumList
		/// to display them
		/// </summary>
		/// <param name="name">a string that is searched for in the media's original names</param>
        private void ShowMediasByName(string name)
        {
            manager.FindMediaByName(name);
            this.mediumList.Items.Clear();
            this.mediumList.Items.AddRange(TransformMediaListToListViewData(manager.Medias));
            if (manager.Medias.Count > 0)
            {
                this.mediumList.Items[0].Selected = true;
                this.mediumList.Select();
            }
            else
            {
                ClearMediaDetails();
            }
        }

		/// <summary>
		/// Cleares all the fields filled for the currently displayed media.
		/// </summary>
        private void ClearMediaDetails()
        {
            this.originalNameTextBox.Tag = null;
            this.originalNameTextBox.Text = "";
            this.translatedNameTextBox.Text = "";
            this.countryTextBox.Text = "";
            this.releaseDatePicker.Value = DateTime.Now;
            this.lengthPicker.Value = 0;
            this.directorTextBox.Text = "";
            this.contentTextBox.Text = "";
            this.ratingUpDown.Value = 0;
            this.genreListBox.Items.Clear();
            this.castListBox.Items.Clear();
            this.pctCover.Image = Properties.Resources.NoPicture;
            this.pctCover.Tag = "NoPicture";
        }

		/// <summary>
		/// Transforms the list of Media clases into a ListViewItem array representation, that can be displayed
		/// in a ListView form
		/// </summary>
		/// <param name="medias">The List of Media classes that is to be transformed</param>
		/// <returns>ListViewItem array of Media classes</returns>
        private ListViewItem[] TransformMediaListToListViewData(IList<Media> media)
        {

            List<ListViewItem> temp = new List<ListViewItem>();

            foreach (var medium in media)
            {
                ListViewItem item1 = new ListViewItem(medium.OriginalName);
                item1.Tag = medium.Id;
                item1.SubItems.Add(medium.Rating.ToString());
                item1.SubItems.Add(string.Format("{0:d.M.yyyy}", medium.ReleaseDate));
                item1.SubItems.Add(medium.Country);

                temp.Add(item1);
            }

            return temp.ToArray<ListViewItem>();
        }

		/// <summary>
		/// an action performed after selecting certain Item in the ListView. It loads info of the selected
		/// Media and displays it in the 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void mediaListItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
                return;

            SetDetailInfoAfterSelection(manager.Medias.First(x => x.Id == ((long)e.Item.Tag)));
            tabControl.SelectedIndex = 0;
            originalNameTextBox_KeyDown(null, null);
        }

		/// <summary>
		/// sets all the attributes from the given Media into corresponding fields
		/// </summary>
		/// <param name="selectedMedia">medium whose attributes are displayed</param>
        private void SetDetailInfoAfterSelection(Media selectedMedia)
        {
            this.originalNameTextBox.Tag = selectedMedia; //prasacina najvacsieho zrna
            this.originalNameTextBox.Text = selectedMedia.OriginalName;
            this.translatedNameTextBox.Text = selectedMedia.TranslatedName;
            this.countryTextBox.Text = selectedMedia.Country;
            this.releaseDatePicker.Value = selectedMedia.ReleaseDate;
            this.lengthPicker.Value = selectedMedia.Length;
            this.directorTextBox.Text = selectedMedia.Director;
            this.contentTextBox.Text = selectedMedia.Content;
            this.ratingUpDown.Value = (decimal)selectedMedia.Rating;
            this.genreListBox.Items.Clear();
            this.castListBox.Items.Clear();
            selectedMedia.Genres.ToList().ForEach(x => this.genreListBox.Items.Add(x));
            selectedMedia.Cast.ToList().ForEach(x => this.castListBox.Items.Add(x));
            this.pctCover.Image = selectedMedia.Image == null ?  Properties.Resources.NoPicture : selectedMedia.Image;
            this.pctCover.Tag = selectedMedia.Image == null ? "NoPicture" : "HasPicture";
        }

		/// <summary>
		/// action performed after the form is closed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void formClosedEvent(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

		/// <summary>
		/// removes selected media after button click
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void removeMediaButton_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Do you really want to delete selected movie?", "Confirm", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.No)
            {
                return;
            }


            if (originalNameTextBox.Tag is Media)
            {
                manager.RemoveMedia(originalNameTextBox.Tag as Media);
            }
        }

        #region Add cast and actors
		/// <summary>
		/// removes selected genre from the genreListBox in the Show panel.
		/// No item is removed if none is selected.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void removeGenre_Click(object sender, EventArgs e)
        {
            if (this.genreListBox.SelectedItem != null)
            {
                object temp = this.genreListBox.SelectedItem;
                this.genreListBox.Items.Remove(temp);
            }
        }

		/// <summary>
		/// removes a selected actor from the castListBox in the Show panel.
		/// No actor is removed if none is selected.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void removeCast_Click(object sender, EventArgs e)
        {
            if (this.castListBox.SelectedItem != null)
            {
                object temp = this.castListBox.SelectedItem;
                this.castListBox.Items.Remove(temp);
            }
            
        }

		/// <summary>
		/// removes a selected genre from the addGenreListBox list in the Add panel.
		/// No genre is removed if none is selected.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addRemoveGenreButton_Click(object sender, EventArgs e)
        {
            if (this.addGenreListBox.SelectedItem != null)
            {
                object temp = this.addGenreListBox.SelectedItem;
                this.addGenreListBox.Items.Remove(temp);
            }
        }

		/// <summary>
		/// removes selected actor from the cast list in the Add panel.
		/// No actor is removed if none is selected.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addRemoveCastButton_Click(object sender, EventArgs e)
        {

            if (this.addCastListBox.SelectedItem != null)
            {
                object temp = this.addCastListBox.SelectedItem;
                this.addCastListBox.Items.Remove(temp);
            }
        }

		/// <summary>
		/// calls for a window to set a new genre to be add into the genreListBox in the View panel
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addGenre_Click(object sender, EventArgs e)
        {
            AddEditActorCast addWindow = new AddEditActorCast(this.genreListBox.Items);
            addWindow.Show();
        }

		/// <summary>
		/// calls for a window to set a new genre to be add into the addGenreListBox listBox in the Add panel
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addAddGenreButton_Click(object sender, EventArgs e)
        {
            AddEditActorCast addWindow = new AddEditActorCast(this.addGenreListBox.Items);
            addWindow.Show();
        }

		/// <summary>
		/// calls for a window to set a new actor to be add into the castListBox in the View panel
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addCast_Click(object sender, EventArgs e)
        {
            AddEditActorCast addWindow = new AddEditActorCast(this.castListBox.Items);
            addWindow.Show();
        }

		/// <summary>
		/// calls for a window to set a new actor to be add into the addCastListBox listBox in the Add panel
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addAddCastButton_Click(object sender, EventArgs e)
        {
            AddEditActorCast addWindow = new AddEditActorCast(this.addCastListBox.Items);
            addWindow.Show();
        }

        #endregion

		/// <summary>
		/// saves all the changes made to a currently selected Media
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void saveChangesButton_Click(object sender, EventArgs e)
        {
            Media media = new Media();
            media.OriginalName = this.originalNameTextBox.Text;
            media.TranslatedName = this.translatedNameTextBox.Text;
            media.Country = this.countryTextBox.Text;
            media.Image = this.pctCover.Tag.ToString().Equals("NoPicture") ? null : this.pctCover.Image;
            media.ReleaseDate = this.releaseDatePicker.Value;
            media.Length = (uint)this.lengthPicker.Value;
            media.Director = this.directorTextBox.Text;
            media.Content = this.contentTextBox.Text;
            media.Rating = (double)this.ratingUpDown.Value;

            List<string> genres = new List<string>();
            foreach (var genre in this.genreListBox.Items)
            {
                genres.Add(genre as string);
            }
            media.Genres = genres;

            List<string> cast = new List<string>();
            foreach (var actor in this.castListBox.Items)
            {
                cast.Add(actor as string);
            }
            media.Cast = cast;

            manager.UpdateMedia(media);
        }

		/// <summary>
		/// Adds a new movie into the database after the "add" button click
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void addNewMovie_Click(object sender, EventArgs e)
        {
			if (this.addOriginalNameTextBox.Text.Equals("")) { // Original Name HAS TO be set
				MessageBox.Show("Original name is not set!");
				this.addOriginalNameTextBox.Focus();
				return;
			}
            Media media = new Media();
            media.OriginalName = this.addOriginalNameTextBox.Text;
            media.TranslatedName = this.addTranslatedNameTextBox.Text;
            media.Country = this.addCountryTextBox.Text;
            media.Image = this.pctCoverAdd.Tag.ToString().Equals("NoPicture") ? null : this.pctCoverAdd.Image;
            media.ReleaseDate = this.addReleaseDatePicker.Value;
            media.Length = (uint)this.addLengthPicker.Value;
            media.Director = this.addDirectorTextBox.Text;
            media.Content = this.addContentTextBox.Text;
            media.Rating = (double)this.addRatingUpDown.Value;

            List<string> genres = new List<string>();
            foreach (var genre in this.addGenreListBox.Items)
            {
                genres.Add(genre as string);
            }
            media.Genres = genres;

            List<string> cast = new List<string>();
            foreach (var actor in this.addCastListBox.Items)
            {
                cast.Add(actor as string);
            }
            media.Cast = cast;

            manager.CreateMedia(media);
            ClearAddPanel();
        }

		/// <summary>
		/// clears all the fields in the Add media panel
		/// </summary>
        private void ClearAddPanel()
        {
            this.addOriginalNameTextBox.Text = "";
            this.addTranslatedNameTextBox.Text = "";
            this.addCountryTextBox.Text = "";
            this.addReleaseDatePicker.Value = DateTime.Now;
            this.addLengthPicker.Value = 0;
            this.addDirectorTextBox.Text = "";
            this.addContentTextBox.Text = "";
            this.addRatingUpDown.Value = 0;
            this.addGenreListBox.Items.Clear();
            this.addCastListBox.Items.Clear();
            this.pctCoverAdd.Image = Properties.Resources.NoPicture;
            this.pctCoverAdd.Tag = "NoPicture";
        }

		/// <summary>
		/// Displays all the media stored in a DB in a listView panel after clicking ShowAll button.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void showAllButton_Click(object sender, EventArgs e)
        {
            ShowAllMedias();
        }

		/// <summary>
		/// Displays all the media containing the text set in a filterNameText field. The search is case sensitive
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void filterByNameButton_Click(object sender, EventArgs e)
        {
            if (filterNameText.Text == "")
            {
                ShowAllMedias();
            }
            else
            {
                ShowMediasByName(filterNameText.Text);
            }
        }

        #region csfd imdb import


        private void pctLoadCoverFromFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog d = new OpenFileDialog();
            d.AddExtension = true;
            d.Title = "Load cover...";
            d.Filter = "JPG images (.jpg)|*.jpg|PNG images (.png)|*.png|GIF images (.gif)|*.gif|TIFF images (.tiff)|*.tiff";
            if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    if (tabControl.SelectedIndex == 0)
                    {
                        pctCover.Image = Image.FromFile(d.FileName).ResizeImageToWidth(127);
                        pctCover.Tag = "HasPicture";
                    }
                    else
                    {
                        pctCoverAdd.Image = Image.FromFile(d.FileName).ResizeImageToWidth(127);
                        pctCover.Tag = "HasPicture";
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("An error occured.", "Cover loadnig error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void pctImportDetails_Click(object sender, EventArgs e)
        {
            contextMenuImport.Show(pctImportDetails, pctImportDetails.PointToClient(Cursor.Position));
        }

        private void iMDbToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((sender as ToolStripMenuItem).DropDownItems.Count != 0) // already loaded
            {
                return;
            }
            IMDbWorker imdb = new IMDbWorker();
            if (tabControl.SelectedIndex == 0)
            {
                imdb.Url = IMDbWorker.CreateSearchUrl(originalNameTextBox.Text);
            }
            else
            {
                imdb.Url = IMDbWorker.CreateSearchUrl(addOriginalNameTextBox.Text);
            }
            imdb.ContentLoaded += new WorkerContentHandler(IMDbSearchContent_Loaded);
            imdb.ContentLoadedFailed += new WorkerErrorHandler(IMDbSearchContent_LoadedFailed);
            imdb.LoadContentAsync();
            this.Cursor = Cursors.WaitCursor;
        }

        private void IMDbSearchContent_LoadedFailed(Exception ex)
        {
            ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).DropDownItems.Clear();
            this.Invoke((MethodInvoker)delegate
            {
                this.Cursor = Cursors.Default;
                ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).DropDownItems.Add("No results");
                contextMenuImport.Show();
                (contextMenuImport.Items[0] as ToolStripMenuItem).ShowDropDown();
                ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).ShowDropDown();
            });
        }

        private void IMDbSearchContent_Loaded(String content)
        {
            Dictionary<string, string> popular = IMDbWorker.GetPopularTitles(content);
            if (popular == null)
            {
                IMDbSearchContent_LoadedFailed(new Exception("No results"));
                return;
            }
            ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).DropDownItems.Clear();
            foreach (KeyValuePair<string, string> itm in popular)
            {
                ToolStripMenuItem itm2 = new ToolStripMenuItem(itm.Value);
                itm2.Tag = itm.Key;
                itm2.Click += new EventHandler(delegate(object sender, EventArgs e)
                {
                    IMDbWorker worker = new IMDbWorker((sender as ToolStripMenuItem).Tag.ToString());
                    worker.ContentLoaded += new WorkerContentHandler(IMDbInfo_Loaded);
                    worker.LoadContentAsync();
                    this.Cursor = Cursors.WaitCursor;
                });
                this.Invoke((MethodInvoker)delegate
                {
                    ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).DropDownItems.Add(itm2);
                });
            }
            this.Invoke((MethodInvoker)delegate
            {
                this.Cursor = Cursors.Default;
                contextMenuImport.Show();
                (contextMenuImport.Items[0] as ToolStripMenuItem).ShowDropDown();
                ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).ShowDropDown();
            });

        }

        private void IMDbInfo_Loaded(String content)
        {
            IMDbWorker imdb = new IMDbWorker(IMDbWorker.GetCoverURL(content));
            imdb.CoverLoaded += new WorkerImageHandler(Cover_Loaded);
            imdb.LoadCoverAsync();
            this.Invoke((MethodInvoker)delegate
            {
                this.Cursor = Cursors.Default;
                if (tabControl.SelectedIndex == 0)
                {
                    MovingPicture movie;
                    movie = IMDbWorker.GetMovieDetails(content);
                    //originalNameTextBox.Text = movie.OriginalName ?? "";
                    translatedNameTextBox.Text = movie.TranslatedName ?? "";
                    countryTextBox.Text = movie.Country ?? "";
                    lengthPicker.Value = movie.Length;
                    directorTextBox.Text = movie.Director ?? "";
                    releaseDatePicker.Value = movie.ReleaseDate < releaseDatePicker.MinDate ? releaseDatePicker.MinDate : movie.ReleaseDate;
                    ratingUpDown.Value = Convert.ToDecimal(movie.Rating);
                    contentTextBox.Text = movie.Content ?? "";
                    genreListBox.Items.Clear();
                    if (movie.Genres != null)
                    {
                        foreach (String item in movie.Genres)
                        {
                            genreListBox.Items.Add(item);
                        }
                    }
                    castListBox.Items.Clear();
                    if (movie.Cast != null)
                    {
                        foreach (String item in movie.Cast)
                        {
                            castListBox.Items.Add(item);
                        }
                    }
                }
                else
                {
                    MovingPicture movie;
                    movie = IMDbWorker.GetMovieDetails(content);
                    addOriginalNameTextBox.Text = movie.OriginalName ?? "";
                    addTranslatedNameTextBox.Text = movie.TranslatedName ?? "";
                    addCountryTextBox.Text = movie.Country ?? "";
                    addLengthPicker.Value = movie.Length;
                    addDirectorTextBox.Text = movie.Director ?? "";
                    addReleaseDatePicker.Value = movie.ReleaseDate < addReleaseDatePicker.MinDate ? addReleaseDatePicker.MinDate : movie.ReleaseDate;
                    addRatingUpDown.Value = Convert.ToDecimal(movie.Rating);
                    addContentTextBox.Text = movie.Content ?? "";
                    addGenreListBox.Items.Clear();
                    if (movie.Genres != null)
                    {
                        foreach (String item in movie.Genres)
                        {
                            addGenreListBox.Items.Add(item);
                        }
                    }
                    addCastListBox.Items.Clear();
                    if (movie.Cast != null)
                    {
                        foreach (String item in movie.Cast)
                        {
                            addCastListBox.Items.Add(item);
                        }
                    }
                }
            });
        }

        private void cSFDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((sender as ToolStripMenuItem).DropDownItems.Count != 0) // already loaded
            {
                return;
            }
            CSFDWorker csfd = new CSFDWorker();
            if (tabControl.SelectedIndex == 0)
            {
                csfd.Url = CSFDWorker.CreateSearchUrl(originalNameTextBox.Text);
            }
            else
            {
                csfd.Url = CSFDWorker.CreateSearchUrl(addOriginalNameTextBox.Text);
            }
            csfd.ContentLoaded += new WorkerContentHandler(CSFDSearchContent_Loaded);
            csfd.ContentLoadedFailed += new WorkerErrorHandler(CSFDSearchContent_LoadedFailed);
            csfd.LoadContentAsync();
            this.Cursor = Cursors.WaitCursor;
        }

        private void CSFDSearchContent_LoadedFailed(Exception ex)
        {
            ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).DropDownItems.Clear();
            this.Invoke((MethodInvoker)delegate
            {
                this.Cursor = Cursors.Default;
                ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).DropDownItems.Add("No results");
                contextMenuImport.Show();
                (contextMenuImport.Items[0] as ToolStripMenuItem).ShowDropDown();
                ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).ShowDropDown();
            });
        }

        private void CSFDSearchContent_Loaded(String content)
        {
            Dictionary<string, string> found = CSFDWorker.GetFoundTitles(content);
            if (found == null)
            {
                CSFDSearchContent_LoadedFailed(new Exception("No results"));
                return;
            }
            ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).DropDownItems.Clear();
            foreach (KeyValuePair<string, string> itm in found)
            {
                ToolStripMenuItem itm2 = new ToolStripMenuItem(itm.Value);
                itm2.Tag = itm.Key;
                itm2.Click += new EventHandler(delegate(object sender, EventArgs e)
                {
                    IMDbWorker worker = new IMDbWorker((sender as ToolStripMenuItem).Tag.ToString());
                    worker.ContentLoaded += new WorkerContentHandler(CSFDInfo_Loaded);
                    worker.LoadContentAsync();
                    this.Cursor = Cursors.WaitCursor;
                });
                this.Invoke((MethodInvoker)delegate
                {
                    ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).DropDownItems.Add(itm2);
                });
            }
            this.Invoke((MethodInvoker)delegate
            {
                this.Cursor = Cursors.Default;
                contextMenuImport.Show();
                (contextMenuImport.Items[0] as ToolStripMenuItem).ShowDropDown();
                ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).ShowDropDown();
            });
        }

        private void Cover_Loaded(Image img)
        {
            this.Invoke((MethodInvoker)delegate
            {
                if (tabControl.SelectedIndex == 0)
                {
                    pctCover.Image = img.ResizeImageToWidth(127);
                    pctCover.Tag = "HasPicture";
                }
                else
                {
                    pctCoverAdd.Image = img.ResizeImageToWidth(127);
                    pctCoverAdd.Tag = "HasPicture";
                }
            });
        }

        private void CSFDInfo_Loaded(String content)
        {
            CSFDWorker csfd = new CSFDWorker(CSFDWorker.GetCoverURL(content));
            csfd.CoverLoaded += new WorkerImageHandler(Cover_Loaded);
            csfd.LoadCoverAsync();
            MovingPicture movie = CSFDWorker.GetMovieDetails(content); ;
            this.Invoke((MethodInvoker)delegate
            {
                this.Cursor = Cursors.Default;
                if (tabControl.SelectedIndex == 0)
                {
                    //originalNameTextBox.Text = movie.OriginalName ?? "";
                    translatedNameTextBox.Text = movie.TranslatedName ?? "";
                    countryTextBox.Text = movie.Country ?? "";
                    lengthPicker.Value = movie.Length;
                    directorTextBox.Text = movie.Director ?? "";
                    releaseDatePicker.Value = movie.ReleaseDate < releaseDatePicker.MinDate ? releaseDatePicker.MinDate : movie.ReleaseDate;
                    ratingUpDown.Value = Convert.ToDecimal(movie.Rating);
                    contentTextBox.Text = movie.Content ?? "";
                    genreListBox.Items.Clear();
                    if (movie.Genres != null)
                    {
                        foreach (String item in movie.Genres)
                        {
                            genreListBox.Items.Add(item);
                        }
                    }
                    castListBox.Items.Clear();
                    if (movie.Cast != null)
                    {
                        foreach (String item in movie.Cast)
                        {
                            castListBox.Items.Add(item);
                        }
                    }
                }
                else
                {
                    addOriginalNameTextBox.Text = movie.OriginalName ?? "";
                    addTranslatedNameTextBox.Text = movie.TranslatedName ?? "";
                    addCountryTextBox.Text = movie.Country ?? "";
                    addLengthPicker.Value = movie.Length;
                    addDirectorTextBox.Text = movie.Director ?? "";
                    addReleaseDatePicker.Value = movie.ReleaseDate < addReleaseDatePicker.MinDate ? addReleaseDatePicker.MinDate : movie.ReleaseDate;
                    addRatingUpDown.Value = Convert.ToDecimal(movie.Rating);
                    addContentTextBox.Text = movie.Content ?? "";
                    addGenreListBox.Items.Clear();
                    if (movie.Genres != null)
                    {
                        foreach (String item in movie.Genres)
                        {
                            addGenreListBox.Items.Add(item);
                        }
                    }
                    addCastListBox.Items.Clear();
                    if (movie.Cast != null)
                    {
                        foreach (String item in movie.Cast)
                        {
                            addCastListBox.Items.Add(item);
                        }
                    }
                }
            });
        }

        private void originalNameTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[0] as ToolStripMenuItem).DropDownItems.Clear();
            ((contextMenuImport.Items[0] as ToolStripMenuItem).DropDownItems[1] as ToolStripMenuItem).DropDownItems.Clear();
        }

        private void originalNameTextBox_MouseClick(object sender, MouseEventArgs e)
        {
            originalNameTextBox_KeyDown(null, null);
        }



        private void addOriginalNameTextBox_TextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(addOriginalNameTextBox.Text))
            {
                pctImportDetailsAdd.Enabled = false;
                pctImportDetailsAdd.Visible = false;
            }
            else
            {
                pctImportDetailsAdd.Enabled = true;
                pctImportDetailsAdd.Visible = true;
            }
        }

        private void originalNameTextBox_TextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(originalNameTextBox.Text))
            {
                pctImportDetails.Enabled = false;
                pctImportDetails.Visible = false;
            }
            else
            {
                pctImportDetails.Enabled = true;
                pctImportDetails.Visible = true;
            }
        }

        #endregion


		/// <summary>
		/// handles the import of all media in the given format from a selected file after clicking the "import" choice of the File menu.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void importToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            IO.ImportExportManager io = new IO.ImportExportManager();
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "";

            foreach (IO.IIOFactory fact in io.ioFactories)
            {
                fileDialog.Filter += " " + fact.FileType + " files (*." + fact.FileType.ToLower() + ")|*." + fact.FileType.ToLower();
                if (!object.ReferenceEquals(fact, io.ioFactories.Last()))
                    fileDialog.Filter += "|";
            }
            fileDialog.RestoreDirectory = true;

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                io.FileName = fileDialog.FileName;
                
                ConfirmForm dialog = new ConfirmForm();
                dialog.TitleDialog = "Media already exists";
                DialogResult result = DialogResult.Retry;
                
                foreach (Media medium in io.loadData())
                {
                    if (manager.FindMediaById(medium.Id) == null)
                    {
                        manager.CreateMedia(medium);
                    }
                    else
                    {
                        
                        dialog.LblDialog = "A medium \"" + medium.OriginalName + "\" already exists in your database. Do you want to update all movie info?";
                        
                        if (result != DialogResult.OK)
                            result = dialog.ShowDialog();

                        if (result == DialogResult.Yes || result == DialogResult.OK)
                            manager.UpdateMedia(medium);
                        else if (result == DialogResult.Cancel)
                            break;

                    }
                }

            }
        }

		/// <summary>
		/// handles the export of all media into the given format after clicking the "export" choice of the File menu.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void exportToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            IO.ImportExportManager io = new IO.ImportExportManager();
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Filter = "";

            foreach (IO.IIOFactory fact in io.ioFactories)
            {
                fileDialog.Filter += " " + fact.FileType + " files (*." + fact.FileType.ToLower() + ")|*." + fact.FileType.ToLower();
                if (!object.ReferenceEquals(fact, io.ioFactories.Last()))
                    fileDialog.Filter += "|";
            }
            fileDialog.RestoreDirectory = true;

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                io.FileName = fileDialog.FileName;
                io.saveData(manager.FindAllMedias());
            }
            
        }

    }
}
